package timetracker.server;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import timetracker.client.ContragentService;
import timetracker.client.database.Contragent;
import timetracker.client.database.Task;
import timetracker.server.database.PMF;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class ContragentServiceImpl extends RemoteServiceServlet implements ContragentService{
	
	@Override
	public Contragent contragentSave(Contragent contragent){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		try {
			pm.makePersistent(contragent);
		} finally {
			pm.close();
		}
		
		return contragent;
	}
	
	public Contragent getContragentByKey(Long key){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		Contragent contragent = new Contragent();
		if (key == null)
			return contragent;
		
		try {
			contragent = (Contragent) pm.getObjectById(key);
		} finally {
			pm.close();
		}
		
		return contragent;
	}
	
	public List<Contragent> getAllContragents(){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query q = pm.newQuery(Contragent.class);
	    //q.declareParameters("com.google.appengine.api.users.User u");
		
		List<Contragent> contragents = new ArrayList<Contragent>();
		try {
			@SuppressWarnings("unchecked")
			List<Contragent> tmp = (List<Contragent>) q.execute();
	        if (!tmp.isEmpty()) {
	            for (Contragent c : tmp) {
	            	contragents.add(c);
	            }
	        }
	    } finally {
	        q.closeAll();
	    }
		
		return contragents;
	}

	@Override
	public Task taskSave(Task task){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		try {
			pm.makePersistent(task);
		} finally {
			pm.close();
		}
		
		return task;
	}

}
